#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>

#define PORT 8888
#define BUZZER_GPIO 557
#define FLAME_SENSOR_GPIO 558
#define GPIO_Buzzer_Value_PATH "/sys/class/gpio/gpio%d/value"
#define GPIO_Buzzer_Direction_PATH "/sys/class/gpio/gpio%d/direction"
#define GPIO_Flame_Sensor_Value_PATH "/sys/class/gpio/gpio%d/value"
#define GPIO_Flame_Sensor_Direction_PATH "/sys/class/gpio/gpio%d/direction"

// 根据传入值控制蜂鸣器
void control_buzzer(int value) {
    char path_buzzer_value[100];
    sprintf(path_buzzer_value, GPIO_Buzzer_Value_PATH, BUZZER_GPIO);
    FILE *fp = fopen(path_buzzer_value, "w");
    if (fp == NULL) {
        perror("无法控制蜂鸣器");
        return;
    }
    fprintf(fp, "%d", value);
    fclose(fp);
    printf("蜂鸣器设置为 %d\n", value);
}

// 获取火焰传感器的状态
int get_flame_sensor_status() {
    char path_flame_sensor_value[100];
    sprintf(path_flame_sensor_value, GPIO_Flame_Sensor_Value_PATH, FLAME_SENSOR_GPIO);
    int fd = open(path_flame_sensor_value, O_RDONLY);
    if (fd < 0) {
        perror("无法打开火焰传感器数值文件");
        return -1;
    }
    char buffer[2];
    read(fd, buffer, 1);
    close(fd);
    return buffer[0] - '0';
}

// 信号处理函数
void handle_sigint(int sig) {
    control_buzzer(0);
    printf("服务器已终止\n");
    exit(0);
}

int main() {
    signal(SIGINT, handle_sigint);
    signal(SIGTERM, handle_sigint);

    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    int buzzer_status = 0;
    int opt = 1;

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("套接字创建失败");
        exit(EXIT_FAILURE);
    }

    // 设置套接字选项，允许立即重用地址
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("设置套接字选项失败");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定套接字到指定端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("绑定失败");
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 3) < 0) {
        perror("监听失败");
        exit(EXIT_FAILURE);
    }

    printf("服务器正在监听端口 %d\n", PORT);

    while (1) {
        // 接受客户端连接
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("接受客户端连接失败");
            continue;
        }

        printf("新客户端已连接\n");

        // 用子进程处理客户端请求
        pid_t pid = fork();
        if (pid < 0) {
            perror("创建子进程失败");
            close(new_socket);
            continue;
        } else if (pid == 0) {
            // 子进程
            while (1) {
                // 接收客户端发送的指令
                int bytes_read = read(new_socket, buffer, 1024);
                if (bytes_read <= 0) {
                    if (bytes_read == 0) {
                        printf("客户端已断开连接\n");
                    } else {
                        perror("读取指令失败");
                    }
                    break;
                }

                buffer[bytes_read] = '\0';  // 确保字符串以null结尾
                if (strcmp(buffer, "check_flame") == 0) {
                    // 检查火焰传感器状态
                    int flame_status = get_flame_sensor_status();
                    if (flame_status == 0) {
                        // 检测到火焰
                        if (buzzer_status == 0) {
                            control_buzzer(1);
                            buzzer_status = 1;
                        }
                        char response[100];
                        sprintf(response, "异常情况，火灾警告，拨打119！");
                        write(new_socket, response, strlen(response));
                    } else if (flame_status == 1) {
                        // 没有检测到火焰
                        if (buzzer_status == 1) {
                            control_buzzer(0);
                            buzzer_status = 0;
                        }
                        char response[100];
                        sprintf(response, "暂无异常情况");
                        write(new_socket, response, strlen(response));
                    } else {
                        // 传感器读取失败
                        write(new_socket, "火焰传感器读取失败", strlen("火焰传感器读取失败"));
                    }
                } else if (strcmp(buffer, "1") == 0) {
                    // 控制蜂鸣器
                    buzzer_status = buzzer_status == 0 ? 1 : 0;
                    control_buzzer(buzzer_status);
                    char response[100];
                    sprintf(response, "蜂鸣器设置为 %d", buzzer_status);
                    write(new_socket, response, strlen(response));
                } else {
                    write(new_socket, "未知命令", strlen("未知命令"));
                }
            }
            close(new_socket);
            exit(0);
        }
    }

    return 0;
}
